package com.yingjia.yingjiauniversity.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class UtilThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String poolName;
    private final String namePrefix;
    private final boolean isDaemon;


    public UtilThreadFactory(String poolName) {
        this(poolName, false);
    }

    public UtilThreadFactory(String poolName, boolean isDaemon) {
        this.poolName = poolName;
        this.isDaemon = isDaemon;
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
        namePrefix = this.poolName + "-" +
                poolNumber.getAndIncrement() +
                "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (isDaemon) {
            t.setDaemon(true); //作为后台线程运行，随系统生灭
        }
        if (t.getPriority() != Thread.NORM_PRIORITY)
            t.setPriority(Thread.NORM_PRIORITY);
        return t;
    }

}
